﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using IndexMarkSilverlightClient.IndexMarkServiceReference;
using SharedCode.Controls;
using System.ComponentModel;
using System.Windows.Data;
using System.Collections.ObjectModel;

namespace IndexMarkSilverlightClient.Views.Subscribe
{
    public partial class SubscribeWindow : ChildWindow, INotifyPropertyChanged
    {
        private IndexMarkServiceClient client = new IndexMarkServiceClient();
        
        //private string SID = string.Empty;
        private User user = null;
        private SubscriberInfo _subscriberInfo = new SubscriberInfo();
        private SubscriberState subscriberState;

        public event PropertyChangedEventHandler PropertyChanged;

        public SubscriberInfo subscriberInfo
        {
            get { return _subscriberInfo; }
            set
            {
                _subscriberInfo = value;
                RaisePropertyChanged("subscriberInfo");
            }
        }

        public SubscribeWindow(Term CurrentTerm, User user)
        {
            InitializeComponent();

            email.SetBinding(TextBox.TextProperty, new Binding("subscriberInfo.Email") { Source = this, Mode = BindingMode.TwoWay });
            subscriberStatus.SetBinding(CheckBox.IsCheckedProperty, new Binding("subscriberInfo.IsActive") { Source = this, Mode = BindingMode.TwoWay });

            //this.SID = user.SID;
            this.user = user;

            Title += string.Format(" {0} - {1}", CurrentTerm.Start.Year, CurrentTerm.Stop.Year);
            USTUTreeView.IDTerm = CurrentTerm.IDTerm;
            
            USTUTreeView.LoadCompleted += new Controls.ReportsControls.USTUTreeView2.LoadCompletedHandler(USTUTreeView_LoadCompleted);
            USTUTreeView.LoadStarting += new Controls.ReportsControls.USTUTreeView2.LoadStartingHandler(USTUTreeView_LoadStarting);
            USTUTreeView.LoadFailed += new Controls.ReportsControls.USTUTreeView2.LoadFailedHandler(USTUTreeView_LoadFailed);
            
            client.CheckSubscribeCompleted += new EventHandler<CheckSubscribeCompletedEventArgs>(client_CheckSubscribeCompleted);

            client.GetSubscriberInfoCompleted += new EventHandler<GetSubscriberInfoCompletedEventArgs>(client_GetSubscriberInfoCompleted);

            client.SaveSubscriberInfoCompleted += new EventHandler<AsyncCompletedEventArgs>(client_SaveSubscriberInfoCompleted);
        }

        void client_SaveSubscriberInfoCompleted(object sender, AsyncCompletedEventArgs e)
        {
            HideLoadingBar();

            this.DialogResult = true;
        }

        void client_GetSubscriberInfoCompleted(object sender, GetSubscriberInfoCompletedEventArgs e)
        {
            subscriberInfo = e.Result;
            subscriberInfo.State = StateObject.Updated;

            USTUTreeView.CheckRespondents(e.Result.Respondents);
            HideLoadingBar();
        }

        void client_CheckSubscribeCompleted(object sender, CheckSubscribeCompletedEventArgs e)
        {
            subscriberState = e.Result;

            if (e.Result == SubscriberState.Activate || e.Result == SubscriberState.NotActivate)
            {
                HideCreateSubscribeButton();

                USTUTreeView.LoadTree();
            }
            else
            {
                // Если подписки вообще не существует, спрячем панель с адресом элекронной почты
                //ShowCreateSubscribeButton();

                //HideLoadingBar();
                CreateSubscribeButton_Click(sender, new RoutedEventArgs());
            }
        }

        void ShowCreateSubscribeButton()
        {
            mailStackPanel.Visibility = Visibility.Collapsed;
            CreateSubscribeButton.Visibility = Visibility.Visible;
            OKButton.IsEnabled = false;
        }

        void HideCreateSubscribeButton()
        {
            mailStackPanel.Visibility = Visibility.Visible;
            CreateSubscribeButton.Visibility = Visibility.Collapsed;
            OKButton.IsEnabled = true;
        }

        void ShowLoadingBar()
        {
            formButtons.Visibility = Visibility.Collapsed;
            buttonsStackPanel.Visibility = Visibility.Collapsed;
            loadingBar.Visibility = Visibility.Visible;
        }

        void HideLoadingBar()
        {
            formButtons.Visibility = Visibility.Visible;
            buttonsStackPanel.Visibility = Visibility.Visible;
            loadingBar.Visibility = Visibility.Collapsed;
        }

        void USTUTreeView_LoadFailed(Exception error)
        {
            HideLoadingBar();
            ErrorWindow ew = new ErrorWindow(error);
            ew.Show();
        }

        void USTUTreeView_LoadStarting()
        {
            ShowLoadingBar();
        }

        void USTUTreeView_LoadCompleted()
        {
            if (subscriberState == SubscriberState.Activate || subscriberState == SubscriberState.NotActivate)
                client.GetSubscriberInfoAsync(user.SID);
            else
                HideLoadingBar();
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            ShowLoadingBar();

            if (subscriberInfo.Respondents == null)
            {
                subscriberInfo.Respondents = new ObservableCollection<Respondent>();
            }
            subscriberInfo.Respondents.Clear();
            foreach(Respondent r in USTUTreeView.Teahers)
            {
                subscriberInfo.Respondents.Add(r);

            }
            client.SaveSubscriberInfoAsync(subscriberInfo);
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void ChildWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ShowLoadingBar();
            client.CheckSubscribeAsync(user.SID);
        }

        private void CreateSubscribeButton_Click(object sender, RoutedEventArgs e)
        {
            HideCreateSubscribeButton();

            USTUTreeView.LoadTree();

            //string domain = string.Empty;
            string name = string.Empty;
            try
            {
                //domain = user.Name.Split('\\')[0];
                name = user.Name.Split('\\')[1];
            }
            catch{}

            subscriberInfo = new SubscriberInfo
            {
                IsActive = true,
                SID = user.SID,
                State = StateObject.Created
            };

            if (user.Domain != string.Empty && name != string.Empty)
            {
                subscriberInfo.Email = string.Format("{0}@{1}", name, user.Domain);
            }
        }

        private void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

